package com.dianping.utils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Map;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.lang3.StringUtils;

public class DzopenSignUtil {

	public static String signTopRequest(Map<String, String> params, String appSecret)
			throws IOException, NoSuchAlgorithmException {

		// 第一步：检查参数是否已经排序
		String[] keys = params.keySet().toArray(new String[0]);
		Arrays.sort(keys);

		// 第二步：把所有参数名和参数值串在一起
		StringBuilder query = new StringBuilder();

		if (StringUtils.isNotEmpty(appSecret)) {
			query.append(appSecret);
		}

		for (String key : keys) {
			String value = params.get(key);
			
			if (key!=null && StringUtils.isNotEmpty(key) && value !=null && StringUtils.isNotEmpty(key)) {
				query.append(key).append(value);
				System.out.println("sign -> "+key+"="+value);
			}
		}

	
		// 第三步：使用MD5/HMAC加密
		byte[] bytes;

		query.append(appSecret);
		bytes = encryptMD5(query.toString());
		System.out.println("sign str: "+query.toString());
		// 第四步：把二进制转化为小写的十六进制
		return byte2hex(bytes);
	}

	public static byte[] encryptHMAC(String data, String secret) {
		byte[] bytes;
		try {
			SecretKey secretKey = new SecretKeySpec(secret.getBytes("utf-8"), "HmacMD5");
			Mac mac = Mac.getInstance(secretKey.getAlgorithm());
			mac.init(secretKey);
			bytes = mac.doFinal(data.getBytes("utf-8"));
		} catch (Exception e) {
			throw new RuntimeException("Encrypt HMAC error", e);
		}

		return bytes;
	}

	public static byte[] encryptMD5(String info) throws NoSuchAlgorithmException, UnsupportedEncodingException {
		MessageDigest md5 = MessageDigest.getInstance("MD5");
		byte[] infoBytes = info.getBytes("UTF-8");
		md5.update(infoBytes);
		return md5.digest();
	}

	public static String byte2hex(byte[] bytes) {
		StringBuilder sign = new StringBuilder();
		for (int i = 0; i < bytes.length; i++) {
			String hex = Integer.toHexString(bytes[i] & 0xFF);
			if (hex.length() == 1) {
				sign.append("0");
			}
			sign.append(hex.toLowerCase());
		}
		return sign.toString();
	}
}
